import router from '@/router' // 引入路由实例
import store from '@/store' // 引入vuex store实例
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

const whiteList = ['/login', '/404'] // 定义白名单  所有不受权限控制的页面

router.beforeEach(async function (to, from, next) {
    ;
    NProgress.start()
    if (store.getters.token) {
        if (to.path === '/login') {
            next('/')
        } else {
            if (!store.getters.userId) {
                const { roles } = await store.dispatch('user/getUserInfo')
                const routes = await store.dispatch('permission/filterRoutes', roles.menus)
                router.addRoutes([...routes], { path: '*', redirect: '/404', hidden: true })
                next(to.path)
            }
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) > -1) {
            next()
        } else {
            next('/login')
        }
    }
    NProgress.done() // 关闭进度条
})
router.afterEach(function () {
    NProgress.done() // 关闭进度条
})